package com.ruoyi.project.system.device.pdf;

import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Tool;
import com.github.abel533.echarts.code.Trigger;

import com.github.abel533.echarts.series.Line;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.github.abel533.echarts.json.GsonOption;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class GenerateLineController {
    /*@Autowired
    private MainInfoService MainInfoService;*/

    private static final String JSpath = "D:\\exportPdf\\echarts-convert\\echarts-convert.js";
    
    /*@RequestMapping(value = "/echartsPictures",method = RequestMethod.POST)
    public void getHxpInfoList() throws Exception{
        String nowDate = DateUtil.formatYesterday(new Date());
        //查询所有实例
        List<String> unit=MainInfoService.getLocationChartsName(locationCharts);
        //标题
        String [] types =unit.toArray(new String[]{});
        //X轴
        String [] valXis = {"出库", "入库"};
        //遍历实例，获取所有实例的图表数据list
        List<Float> list=new ArrayList<>();
        for (int i = 0; i < unit.size(); i++) {
            for (int j = 0; j < valXis.length; j++) {
                if (j==0){
                    locationCharts.setBeforeDate(nowDate);
                    locationCharts.setTransactionType("0");
                    locationCharts.setUnit(unit.get(i));
                    list.add(Float.valueOf((MainInfoService.getLocationChartsValue(locationCharts))));
                }
                if (j==1){
                    locationCharts.setBeforeDate(nowDate);
                    locationCharts.setTransactionType("1");
                    locationCharts.setUnit(unit.get(i));
                    list.add(Float.valueOf((MainInfoService.getLocationChartsValue(locationCharts))));
                }
            }
        }
        //list转换成list数组
        List<float[]> datas=listToArray(list,2);
        String title = "库位移动量趋势图";
        GsonOption option = new GsonOption();
        option.itemStyle().normal().label().show(true);
        option.title().text(title).subtext (nowDate).x("left") ; // 大标题、小标题、位置
        option.color("#0361F8","#FD7624", "#8B2FFB", "#B623D2","#85C07A","#52B3FB","#00C892","#F88600");//折线图颜色
        option.tooltip().trigger(Trigger.axis) ; // 在轴上触发提示数据
        //工具栏
        option.toolbox().show(true).feature(Tool.saveAsImage) ; // 显不保存为图片
        option.legend(types) ;// 图例
        CategoryAxis category = new CategoryAxis () ; // 轴分类
        category.data(valXis);
        category .boundaryGap (false) ; //起始和结束两端空白策略
        //循环数据
        for (int i = 0; i < types.length; i++) {
            Line line = new Line(); // 几条线,几个对象
            String type = types[i];
            line.itemStyle().normal().label().show(true);
            line.name(type);
            for (int j = 0; j < 2; j++)
                line.data(datas.get(i)[j]);
            option.series(line);
        }
        option.xAxis(category);// x轴
        option.yAxis(new ValueAxis());//y轴
        Map<String,Object> resultMap=new HashMap<>();
        generateEChart(new Gson().toJson(option), resultMap);
    }*/

    public static String generateEChart(String options, Map<String,Object> resultMap) {
    	//获取昨天时间
        String nowDate = "20240728";//DateUtil.formatYesterday(new Date());
        String dataPath = writeFile(options);
        String fileName= nowDate+"库位移动量趋势图"+ ".png";
        String path = "D:\\exportPdf\\" +fileName;
        try {
            File file = new File(path);     //文件路径（路径+文件名）
            if (!file.exists()) {   //文件不存在则创建文件，先创建目录
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            String cmd = "D:\\exportPdf\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe " + JSpath + " -txtPath " + dataPath + "-picTmpPath D:\\exportPdf\\111.png -picPath D:\\exportPdf\\222.png " ;
            System.out.printf("cmd:"+cmd);
            Process process = Runtime.getRuntime().exec(cmd);
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                System.out.println("line++++++++++++++++++++"+line);
            }
            input.close();

        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            return path;
        }
    }

    public static String writeFile(String options) {
        String dataPath="D:\\exportPdf\\"+ UUID.randomUUID().toString().substring(0, 8) +".text";
        try {
            /* 写入Txt文件 */
            File writename = new File(dataPath); // 相对路径，如果没有则要建立一个新的output.txt文件
            if (!writename.exists()) {   //文件不存在则创建文件，先创建目录
                File dir = new File(writename.getParent());
                dir.mkdirs();
                writename.createNewFile(); // 创建新文件
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(options); // \r\n即为换行
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后记得关闭文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataPath;
    }

    public static List<float[]> listToArray(List<Float> list,int bccSize){
        List<float []> list2 = new ArrayList<float []>();
        float arr[]=null;
        for(int j=1,len=list.size()+1;j<len;j++){
            if(j==1){
                if(len>bccSize){ //初始化数组大小
                    arr=new float[bccSize];
                }else{
                    arr=new float[len-1];
                }
            }
            arr[j-(bccSize*list2.size())-1]= list.get(j-1);  //给数组赋值
            if(j%bccSize==0){
                list2.add(arr);  //数组填值满后放到集合中
                if(len-j-1>bccSize){
                    arr=new float[bccSize];
        //不允许数组有空值创建最后一个数组的大小(如果都要一定大小可以去掉)
                }else{
                    arr=new float[len-(bccSize*list2.size())-1];
                }
            }else if(j==len-1){
                list2.add(arr);//最后一个数组可能没有规定大小
            }
        }

        return list2;
    }

    public static void main(String[] args) {
        String json = "option = {\n" +
                "  xAxis: {\n" +
                "    type: 'category',\n" +
                "    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n" +
                "  },\n" +
                "  yAxis: {\n" +
                "    type: 'value'\n" +
                "  },\n" +
                "  series: [\n" +
                "    {\n" +
                "      data: [120, 200, 150, 80, 70, 110, 130],\n" +
                "      type: 'bar'\n" +
                "    }\n" +
                "  ]\n" +
                "};";
        generateEChart(json,null);
    }
}

